import util from './util.js';
import authLogin from './autuLogin.js';
import { HEADER } from './../config.js';
/**
 * 发送请求
 */
function request(api, method, data, { noAuth = false, noVerify = false,_api='api/',url=''}) {
  let Url = url ? url : getApp().globalData.url, header = HEADER;
  console.log("noAuth",noAuth)
  if (!noAuth) {
    // 登录过期自动登录
    if (!util.checkLogin()) return authLogin().then((e) => {
      return request(api, method, data, { noAuth, noVerify, _api,url });
    });
  }
  // debugger
  if (getApp().globalData.token) header['auth'] = getApp().globalData.token;
  return new Promise((reslove, reject) => {
	console.log("request+Data",data)
    uni.request({
      url: Url + _api + api,
      method: method.toUpperCase() || 'GET',
      header: header,
      data: data.AppId?{...data}:( {AppId:getApp().globalData.appid,...data} || {}),
      success: (res) => {
        if (noVerify)
          reslove(res.data);
        else if (res.data.status == 200 || res.data.status == 500 || res.data.result || res.data.code == 1 || res.data.code == 200) {
          reslove(res.data);
        } else if (('' + res.data.status).includes(40000)) {
          util.logout()
          util.checkLogin()
        } else
          reject(res.data.message || '系统错误');
      },
      fail: (msg) => {
        reject('请求失败');
      }
    })
  });
}
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt) => request(api, method, data, opt || {})
});




export default request;


